<template>
	<view>
		<np-navbar :shadow="false">
			<view class="np-search-box">
				<text class="np-search-icon npIcon-search"></text>
				<input class="np-search-input" @input="inputChange" v-model="keyword" @confirm="inputConfirm" type="text"
				 placeholder="输入标题或关键字搜索" confirm-type="search"></input>
				<text v-show="keyword" class="np-delete-icon npIcon-backdelete" @click="delKey"></text>
			</view>
			<view slot="view" v-if="showList">
				<search-sort :list="apiList" @change="sortClick" @coupon="couponClick"></search-sort>
			</view>
		</np-navbar>
		<view v-if="showKeywordList">
			<view class="np-word-box" :style="{ top:showList ? topHeight + sortHeight + 'px'  : topHeight + 'px' }">
				<view class="np-word-item" hover-class="word-hover" v-for="(row,index) in keywordList" :key="index" @click="keywordClick(row.keyword)">
					<rich-text :nodes="row.htmlStr"></rich-text>
					<image class="word-item-right" src="/static/images/search/jt.png"></image>
				</view>
			</view>
		</view>
		<view v-if="!showList">
			<view class="np-keyword-box">
				<view class="keyword-block" v-if="oldKeywordList.length>0">
					<view class="keyword-block-title">
						<text class="title-text">历史搜索</text>
						<image class="title-image" src="/static/images/search/delete.png" @click="oldDelete"></image>
					</view>
					<view class="keyword-item">
						<view class="keyword-item-text" v-for="(key,index) in oldKeywordList" :key="index" @click="keywordClick(key)">
							<text class="keyword-item-key">{{key}}</text>
						</view>
					</view>
				</view>
				<view class="keyword-block">
					<view class="keyword-block-title">
						<text class="title-text">热门搜索</text>
						<image class="title-image" :src="'/static/images/search/attention'+forbid+'.png'" @click="hotToggle"></image>
					</view>
					<view class="keyword-item" v-if="forbid==''">
						<view class="keyword-item-text" v-for="(key,index) in hotKeywordList" :key="index" @click="keywordClick(key)">
							<text class="keyword-item-key">{{key}}</text>
						</view>
					</view>
					<text v-else class="hide-tip">当前搜热门搜索已隐藏</text>
				</view>
			</view>
		</view>
		<view v-if="globalConfig.api_list">
			<mescroll-body ref="mescrollRef" :top="listTop" :down="downOption" :up="upOption" @init="mescrollInit" @down="downCallback"
				 @up="upCallback" @emptyclick="downCallback">
					<view v-if="showList">
						<np-list-one :goodsList="goodsList" :api="api"></np-list-one>
						<np-empty info="没有加载到数据" :showBtn="showEmptyBtn" @click="downCallback" v-if="goodsList.length === 0 && isEmpty"></np-empty>
					</view>
			</mescroll-body>
		</view>
	</view>
</template>

<script>
	import base from '@/common/base.js'
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import searchSort from './components/sort.vue'
	let loading = false;
	export default {
		mixins: [base,MescrollMixin],
		components: {
			searchSort
		},
		data() {
			return {
				showListData: true,
				goodsList: [],
				keywordList: [],
				oldKeywordList: [],
				forbid: '',
				sortType: 0,
				page: 1,
				isCoupon: false,
				loading: false,
				showKeywordList: false,
				isEmpty: false,
				emptyText: '',
				showEmptyBtn: false,
				downOption: {
					auto: false
				},
				upOption: {
					auto: false,
					page: {
						num: 0,
						size: 20
					},
					noMoreSize: 4,
					empty: {
						tip: '~ 空空如也 ~', // 提示
						btnText: '重新加载'
					}
				},
				listTop: 150,
				topHeight: 0,
				sortHeight: 30,
				api: "", 
				hotKeywordList: [],
				apiList: [],
				keyword: "",
				searchKey: "",
				showList: false,
				fromOption: false,
			}
		},
		onLoad(option) {
			this.loadOldKeyword();
			if (option.title && option.keyword) {
				this.searchKey = option.keyword;
				this.keyword = option.title;
				this.fromOption = true;
			} else if (option.keyword) {
				this.searchKey = this.keyword = option.keyword;
				this.fromOption = true;
			}
			// #ifdef MP-WEIXIN||MP-QQ
			if (this.globalConfig.wechat_mod == 0 &&  this.globalConfig.showShMode) {
				this.showListData = false;
			}
			// #endif
		},
		onReady() {
			this.initData();
		},
		watch: {
			globalConfig() {
				if (this.globalConfig.api_list) {
					this.initData()
				}
			}
		},
		onShareAppMessage(res) {
			let parentId = this.$config.getParentId();
			if (this.hasLogin) {
				parentId = this.userInfo.id;
			}
			let path = '/pages/search/search?uid=' + parentId;
			let title = "优惠券超级搜索";
			if (this.searchKey) {
				title = this.searchKey + '优惠券';
				path = path + '&keyword=' + this.searchKey
			}
			return {
				title: title,
				path: path,
			};
		},
		methods: {
			initData(){
				this.setSearchData();
			},
			setSearchData() {
				if (!this.globalConfig.api_list)return;
				let result = this.globalConfig;
				this.hotKeywordList = result.hot;
				this.apiList = [];
				let apiList = result.api_list;
				// #ifdef MP-WEIXIN||MP-QQ
				if (this.globalConfig.wechat_mod == 0 && this.globalConfig.showShMode) {
					apiList = result.sh_api_list;
				}
				// #endif
				apiList.forEach((item) => {
					if (item.disabled) {
						this.api = item.api;
					}
					this.apiList.push(item);
				});
				if (apiList.length == 1) {
					this.listTop = 70;
				} else {
					this.sortHeight = 70;
				}
				if (this.keyword) {
					this.upCallback();
				}
				if (this.fromOption) {
					this.showList = true;
				}
			},
			keywordClick(keyword) {
				this.searchKey = this.keyword = keyword;
				this.saveKeyword(keyword);
				this.showKeywordList = false;
				this.searchKey = keyword;
				this.downCallback();
			},
			inputChange(event) {
				var keyword = event.detail ? event.detail.value : '';
				if (!keyword) {
					this.keywordList = [];
					this.showKeywordList = false;
					return;
				}
				this.showKeywordList = true;
				this.$http.get('api/default/word', {
					params: {'keyword': keyword}
				}).then((res) => {
					if (res) {
						this.keywordList = this.drawCorrelativeKeyword(res, keyword);
					}
				}).catch((error) => {});
			},
			inputConfirm() {
				uni.hideKeyboard();
				if (this.keyword) {
					this.searchKey = this.keyword;
				}
				this.showKeywordList = false;
				this.saveKeyword(this.searchKey);
				this.downCallback();
			},
			downCallback() {
				this.page = 1;
				this.min_id = 1;
				this.goodsList = [];
				this.mescroll.resetUpScroll();
			},
			upCallback(page) {
				if (!this.searchKey) {
					this.mescroll.endErr();
					return;
				}
				if (loading) {
					return;
				}
				loading = true;
				this.showList = true;
				this.emptyText = '';
				this.isEmpty = false;
				this.showEmptyBtn = false;
				let sendData = {};
				switch (this.api) {
					case 'ali':
						sendData.cate_id = 1;
						break;
					case 'jd':
						sendData.cate_id = 2;
						break;
					case 'pdd':
						sendData.cate_id = 3;
						break;
				}
				sendData.keyword = this.searchKey;
				sendData.is_coupon = this.isCoupon;
				sendData.sort_type = this.sortType;
				sendData.page = this.page;
				sendData.min_id = this.min_id;

				this.$http.get('api/default/search', {params: sendData}).then((res) => {
					loading = false;
					let hasNext = true;
					if (!("list" in res) || res.list.length < 20) {
						hasNext = false;
					}
					this.mescroll.endSuccess(res.list.length, hasNext);
					this.page = this.page + 1;
					this.min_id = res.min_id;
					let goodsList = res.list;
					goodsList.forEach(item => {
						this.goodsList.push(item);
					});
				}).catch((error) => {
					loading = false;
					this.isEmpty = true;
					this.showEmptyBtn = true;
					this.mescroll.endErr();
				});
			},
			sortClick(e) {
				this.api = e.api;
				this.sortType = e.sortType;
				this.page = 1;
				this.min_id = 1;
				this.goodsList = [];
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				});
				this.downCallback();
			},
			couponClick(e) {
				this.isCoupon = e;
				this.page = 1;
				this.min_id = 1;
				this.goodsList = [];
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 0
				});
				this.downCallback();
			},
			drawCorrelativeKeyword(keywords, keyword) {
				var len = keywords.length,
					keywordArr = [];
				for (var i = 0; i < len; i++) {
					var row = keywords[i];
					var html = row[0].replace(keyword, "<span style='color: #ff5500;'>" + keyword + "</span>");
					html = '<div>' + html + '</div>';
					var tmpObj = {
						keyword: row[0],
						htmlStr: html
					};
					keywordArr.push(tmpObj)
				}
				return keywordArr;
			},
			loadOldKeyword() {
				uni.getStorage({
					key: 'OldKeys',
					success: (res) => {
						var OldKeys = res.data;
						this.oldKeywordList = OldKeys;
					}
				});
			},
			saveKeyword(keyword) {
				uni.getStorage({
					key: 'OldKeys',
					success: (res) => {
						var OldKeys = res.data;
						var findIndex = OldKeys.indexOf(keyword);
						if (findIndex == -1) {
							OldKeys.unshift(keyword);
						} else {
							OldKeys.splice(findIndex, 1);
							OldKeys.unshift(keyword);
						}
						OldKeys.length > 20 && OldKeys.pop();
						uni.setStorage({
							key: 'OldKeys',
							data: OldKeys
						});
						this.oldKeywordList = OldKeys;
					},
					fail: (e) => {
						var OldKeys = [keyword];
						uni.setStorage({
							key: 'OldKeys',
							data: OldKeys
						});
						this.oldKeywordList = OldKeys;
					}
				});
			},
			oldDelete() {
				uni.showModal({
					content: '确定清除历史搜索记录？',
					success: (res) => {
						if (res.confirm) {
							this.oldKeywordList = [];
							uni.removeStorage({
								key: 'OldKeys'
							});
						} else if (res.cancel) {

						}
					}
				});
			},
			hotToggle() {
				this.forbid = this.forbid ? '' : '_forbid';
			},
			delKey() {
				this.keyword = '';
				this.showKeywordList = false;
			}
		},
	}
</script>

<style lang="scss">
	.np-search-box {
		width: 600rpx;
		/* #ifdef MP-WEIXIN */
		width: 400rpx;
		margin-right: 100rpx;
		/* #endif */
		/* #ifdef MP-QQ */
		width: 400rpx;
		margin-right: 100rpx;
		/* #endif */
		height: 64rpx;
		background-color: #f5f5f5;
		border-radius: 32rpx;
		display: flex;
		align-items: center;
		padding: 0rpx 20rpx;
	}

	.np-search-icon {
		width: 29rpx;
		height: 28rpx;
		font-size: 28rpx;
		margin-right: 10rpx;
	}

	.np-search-input {
		width: 100%;
		height: 44rpx;
		font-size: 28rpx;
	}

	.np-delete-icon {
		width: 29rpx;
		height: 28rpx;
		font-size: 28rpx;
		margin-left: 10rpx;
	}

	.np-word-box {
		position: fixed;
		left: 0;
		width: 100%;
		z-index: 10;
		padding: 10rpx;
		background-color: #FFFFFF;
	}
	
	.np-word-item {
		width: 100%;
		padding: 20rpx 0;
		border-bottom: 1rpx #f7f7f7 solid;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}
	
	.word-hover {
		background-color: #eee;
	}
	
	.word-item-right {
		width: 60rpx;
		height: 60rpx;
	}
	
	.np-keyword-box{
		width: 100%;
		background-color: #fff;
		border-radius: 20rpx;
		margin-top: 20rpx;
	}
	
	.keyword-block {
		padding: 20rpx;
	}
	
	.keyword-block-title {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.title-text {
		font-size: 26rpx;
		color: #333;
	}
	
	.title-image {
		width: 38rpx;
		height: 38rpx;
	}
	
	.keyword-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		flex-wrap: wrap;
	}
	
	.keyword-item-text {
		padding: 5rpx 10rpx;
		background-color: rgb(242, 242, 242);
		border-radius: 10rpx;
		margin: 10rpx;
	}
	
	.keyword-item-key {
		font-size: 24rpx;
		color: #6b6b6b;
	}
	
	.hide-tip {
		font-size: 24rpx;
		color: #6b6b6b;
	}
	
	.error {
		height: 300rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		font-size: 26rpx;
		color: #2C405A;
		align-items: center;
	}
</style>
